<template>
  <div style="background: #ececec; padding: 10px">
    <a-spin :spinning="spinning" tip="正在转换中, 请稍等...">
      <a-row :gutter="[8, 8]">
        <a-col :span="12">
          <a-card title="源SQL" :bordered="false">
            <template #extra>
              <a-space :size="16">
                <a-select
                  v-model:value="sourceSelectVal"
                  style="width: 150px"
                  :options="sourceOptions"
                  :allow-clear="true"
                ></a-select>
                <a-button block type="primary" @click="handleTransfer"
                  >转换</a-button
                >
                <a-button block danger type="primary" @click="handleCleanValue"
                  >清空</a-button
                >
              </a-space>
            </template>
            <code-editor
              ref="sourceCodeEditorRef"
              v-model="initSourceSql"
              :theme="'vs-dark'"
              :language="'sql'"
              :read-only="false"
              :font-size="15"
              @handle-model-value="handleModelValue"
            ></code-editor>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="目标SQL" :bordered="false">
            <template #extra>
              <a-space :size="16">
                <a-select
                  v-model:value="targetSelectVal"
                  style="width: 150px"
                  :options="targetOptions"
                  :allow-clear="true"
                ></a-select>
                <a-tooltip title="复制">
                  <a-button
                    :size="'large'"
                    type="primary"
                    shape="circle"
                    @click="handleCopy"
                  >
                    <template #icon>
                      <CopyOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </a-space>
            </template>
            <code-editor
              v-model="targetSql"
              :theme="'vs-dark'"
              :language="'sql'"
              :read-only="true"
              :font-size="15"
            ></code-editor>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
  </div>
</template>

<script setup lang="ts" name="App">
import { CopyOutlined } from "@ant-design/icons-vue"
import useClipboard from "vue-clipboard3"
import { dbTransfer } from "./utils/transfer.js"
import { message } from "ant-design-vue"
import CodeEditor from "@/components/CodeEditor.vue"
// 初始化SQL模板
let initSourceSql = ref(
  "-- sys_user definition\nCREATE TABLE `sys_user` (\n`user_id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户ID',\n`dept_id` bigint DEFAULT NULL COMMENT '部门ID',\n`user_name` varchar(30) NOT NULL COMMENT '用户账号',\n`nick_name` varchar(30) NOT NULL COMMENT '用户昵称',\n`user_type` varchar(2) DEFAULT '00' COMMENT '用户类型（00系统用户）',\n`email` varchar(50) DEFAULT '' COMMENT '用户邮箱',\n`phonenumber` varchar(11) DEFAULT '' COMMENT '手机号码',\n`sex` char(1) DEFAULT '0' COMMENT '用户性别（0男 1女 2未知）',\n`avatar` varchar(100) DEFAULT '' COMMENT '头像地址',\n`password` varchar(100) DEFAULT '' COMMENT '密码',\n`status` char(1) DEFAULT '0' COMMENT '帐号状态（0正常 1停用）',\n`del_flag` char(1) DEFAULT '0' COMMENT '删除标志（0代表存在 2代表删除）',\n`login_ip` varchar(128) DEFAULT '' COMMENT '最后登录IP',\n`login_date` datetime DEFAULT NULL COMMENT '最后登录时间',\n`create_by` varchar(64) DEFAULT '' COMMENT '创建者',\n`create_time` datetime DEFAULT NULL COMMENT '创建时间',\n`update_by` varchar(64) DEFAULT '' COMMENT '更新者',\n`update_time` datetime DEFAULT NULL COMMENT '更新时间',\n`remark` varchar(500) DEFAULT NULL COMMENT '备注',\nPRIMARY KEY (`user_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb3 COMMENT='用户信息表';"
)
// 目标SQL输出
let targetSql = ref("")
// 加载
const spinning = ref<Boolean>(false)
// 源SQL下拉选项
const sourceOptions = ref([
  {
    value: "MySQL",
    label: "MySQL"
  }
])
// 目标SQL下拉选项
const targetOptions = ref([
  {
    value: "PostgreSQL",
    label: "PostgreSQL"
  }
])
// 源SQL下拉初始值
const sourceSelectVal = ref("MySQL")
// 目标SQL下拉初始值
const targetSelectVal = ref("PostgreSQL")
// 源SQL变更监听值
const childSql = ref(undefined)
// 真实源SQL
const sourceSql = computed(() => {
  if (childSql.value != undefined) {
    return childSql.value
  } else {
    return initSourceSql.value
  }
})

const sourceCodeEditorRef = ref()

const { toClipboard } = useClipboard()
// 复制目标SQL
const handleCopy = async () => {
  try {
    await toClipboard(targetSql.value)
    message.success("复制成功")
  } catch (e) {
    console.error(e)
  }
}
/**
 * 转换SQL
 */
function handleTransfer() {
  if (!sourceSelectVal.value || !targetSelectVal.value) {
    message.config({
      top: `100px`
    })
    message.warn("请选择转换SQL类型")
    return
  }
  spinning.value = true
  const targetSqlArray = dbTransfer(sourceSql.value)
  targetSql.value = ""
  for (const item of targetSqlArray) {
    targetSql.value += item
  }
  spinning.value = false
}
/**
 * 实时处理源SQL
 * @param {String} sql 源SQL
 */
function handleModelValue(sql: String) {
  childSql.value = sql
}

function handleCleanValue() {
  sourceCodeEditorRef.value.cleanCodeValue()
}
</script>

<style scoped>
#app {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
